package controllers

import play.api._
import play.api.mvc._
import play.api.Play.current

object Application extends Controller with Secured{

  def index = IsAuthenticated { username => _ =>
    Ok(views.html.index("Your new application is ready."))
  }

  def delete(project: Long) = IsMemberOf(project) { username => _ =>
    //delete
    Ok
  }

  def showUpload = Action {
    Ok(views.html.file("upload"))
  }

  def upload = Action(parse.multipartFormData) { request =>
    request.body.file("picture").map { picture =>
      import java.io.File

      def createDir(name: String): Unit ={
        val file = new File(name)
        if(!file.exists()){
          file.mkdirs()
        }
      }
      createDir("/tmp/picture/")

      val filename = picture.filename
      val contentType = picture.contentType
      picture.ref.moveTo(new File("/tmp/picture/" + filename))
      Ok("File uploaded:" + filename)
    }.getOrElse {
      Redirect(routes.Application.index).flashing(
        "error" -> "Missing file"
      )
    }
  }

  def showImage(name: String) = Action {
    import java.io.File
    val app = Play.application
//    var file = Play.application.getFile("/tmp/picture/"+name)
    val file = new File("/tmp/picture/" + name)
    val source = scala.io.Source.fromFile(file)(scala.io.Codec.ISO8859)
    val byteArray = source.map(_.toByte).toArray
    source.close()

    Ok(byteArray).as("image/jpeg")
  }
}